<route lang="yaml">
meta:
  title: 登录
  constant: true
  layout: false
</route>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import Copyright from '@/layouts/components/Copyright/index.vue';
import useSettingsStore from '@/store/modules/settings';
import useUserStore from '@/store/modules/user';
import defaultValue from './defaultValue';
import { useRequest } from 'vue-hooks-plus';
import API from '@/api/api';
import { getAreaCode } from '@/components/AreaSelect/getAreaTree';
import { useMessage } from '@/hooks/useMessage';

const banner = new URL('../assets/images/login-banner.png', import.meta.url)
  .href;
const logo = new URL('../assets/images/logo.png', import.meta.url).href;
const title = import.meta.env.VITE_APP_TITLE;
import { createPhoneRole, createRequireRole } from '@/utils/rules';
import { useCaptchaCountdown } from '@/hooks/useCaptchaCountdown';

const message = useMessage();
defineOptions({
  name: 'Login',
});

const { disabled, text, startCountdown, stopCountdown } = useCaptchaCountdown();
const route = useRoute();
const router = useRouter();
function onSendCode() {
  if (!loginForm.value.account) {
    return message.error('请输入手机号');
  }
  if (!/1\d{10}/.test(loginForm.value.account)) {
    return message.error('手机号格式不正确');
  }
  startCountdown(() => {
    API.smsController
      .sendsms({
        phone: loginForm.value.account,
        scene: 'LOGIN',
        sig: '78ejdsdkaoeniskkd',
      })
      .then(() => {
        message.success('验证码已发送');
      })
      .catch(() => {
        setTimeout(stopCountdown, 1000);
      });
  });
}
const settingsStore = useSettingsStore();
const userStore = useUserStore();
// 表单类型，login 登录，register 注册，reset 重置密码
const formType = ref('login');
const loading = ref(false);
const redirect = ref(
  route.query.redirect?.toString() ?? settingsStore.settings.home.fullPath
);

// 登录
const loginFormRef = ref<FormInstance>();
const loginForm = ref({
  account: localStorage.login_account || '',
  password: '',
  remember: !!localStorage.login_account,
  platType: 1,
});
const loginRules = ref<FormRules>({
  account: [{ required: true, trigger: 'blur', message: '请输入手机号' }],
  password: [
    { required: true, trigger: 'blur', message: '请输入验证码' },
    { min: 6, max: 6, trigger: 'blur', message: '验证码长度为6位' },
  ],
});
function handleLogin() {
  loginFormRef.value &&
    loginFormRef.value.validate(valid => {
      if (valid) {
        loading.value = true;
        userStore
          .login(loginForm.value)
          .then(() => {
            loading.value = false;
            if (loginForm.value.remember) {
              localStorage.setItem('login_account', loginForm.value.account);
            } else {
              localStorage.removeItem('login_account');
            }
            router.push(redirect.value);
          })
          .catch(() => {
            loading.value = false;
          });
      }
    });
}

// 注册
const registerFormRef = ref<FormInstance>();
const registerForm = ref(defaultValue);
const registerRules = ref<FormRules>({
  resourceType: [createRequireRole()],
  area: [createRequireRole()],
  contactsName: [createRequireRole()],
  contactsPhone: [createRequireRole(), ...createPhoneRole()],
  businessLicense: [createRequireRole()],
  check: [createRequireRole()],
  corporateIdCard: [createRequireRole()],
  corporateIdCardF: [
    createRequireRole(),
    {
      validator: (rule, value, callback) => {
        if (!registerForm.value.corporateIdCardO) {
          callback(new Error('请上传'));
        } else {
          callback();
        }
      },
    },
  ],
});
const registerReq = useRequest(API.organizationController.add, {
  manual: true,
});
function handleRegister() {
  registerFormRef.value &&
    registerFormRef.value.validate(valid => {
      if (valid) {
        if (!registerForm.value.check) {
          return useMessage().error('请同意协议');
        }
        registerReq
          .runAsync({
            ...registerForm.value,
            ...getAreaCode(registerForm.value.area),
            area: undefined,
          })
          .then(res => {
            formType.value = 'login';
            registerForm.value = {};
            useMessage().success('已提交');
          });
      } else {
        useMessage().error('请检查填写项');
      }
    });
}

// 重置密码
const resetFormRef = ref<FormInstance>();
const resetForm = ref({
  account: localStorage.login_account,
  captcha: '',
  newPassword: '',
});
const resetRules = ref<FormRules>({
  account: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
  captcha: [{ required: true, trigger: 'blur', message: '请输入验证码' }],
  newPassword: [
    { required: true, trigger: 'blur', message: '请输入新密码' },
    { min: 6, max: 18, trigger: 'blur', message: '密码长度为6到18位' },
  ],
});
function handleReset() {
  ElMessage({
    message: '重置密码仅提供界面演示，无实际功能，需开发者自行扩展',
    type: 'info',
  });
  resetFormRef.value &&
    resetFormRef.value.validate(valid => {
      if (valid) {
        // 这里编写业务代码
      }
    });
}
</script>

<template>
  <div class="loginPage">
    <div class="bg-banner" />
    <div id="login-box">
      <div
        class="login-banner"
        :class="formType === 'register' ? 'login-banner1' : ''"
        style="background-color: rgb(12 195 175)"
      >
        <img :src="logo" class="logo" />
        <img :src="banner" class="banner" />
      </div>
      <ElForm
        v-show="formType === 'login'"
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
      >
        <div class="title-container">
          <h3 class="title">欢迎来到 {{ title }} ! 👋🏻</h3>
        </div>
        <div>
          <ElFormItem prop="account">
            <ElInput
              v-model="loginForm.account"
              placeholder="请输入手机号"
              type="text"
              tabindex="1"
              maxlength="11"
            >
              <template #prefix>
                <SvgIcon name="i-ri:user-3-fill" />
              </template>
            </ElInput>
          </ElFormItem>
          <ElFormItem prop="password">
            <ElInput
              v-model="loginForm.password"
              placeholder="验证码"
              tabindex="2"
              @keyup.enter="handleLogin"
              maxlength="6"
            >
              <template #prefix>
                <SvgIcon name="i-ic:baseline-verified-user" />
              </template>
              <template #append>
                <ElButton
                  style="width: 102px; text-align: center"
                  :disabled="disabled"
                  @click="onSendCode"
                  >{{ text }}</ElButton
                >
              </template>
            </ElInput>
          </ElFormItem>
        </div>
        <!-- <div class="flex-bar">
          <ElCheckbox v-model="loginForm.remember"> 记住我 </ElCheckbox>
          <ElLink type="primary" :underline="false" @click="formType = 'reset'">
            忘记密码了?
          </ElLink>
        </div> -->
        <ElButton
          :loading="loading"
          type="primary"
          size="large"
          color="rgb(12, 195, 175)"
          style="width: 100%; color: #fff"
          @click.prevent="handleLogin"
        >
          登录
        </ElButton>
        <div class="sub-link">
          <ElLink
            type="primary"
            :underline="false"
            style="width: 100%; color: rgb(12, 195, 175)"
            @click="formType = 'register'"
          >
            机构申请入驻
          </ElLink>
        </div>
      </ElForm>
      <ElForm
        label-width="100px"
        v-show="formType === 'register'"
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="login-form"
        auto-complete="on"
      >
        <div class="title-container">
          <h3 class="title">申请入驻</h3>
        </div>
        <el-steps :active="1" align-center>
          <el-step title="提交入驻信息" />
          <el-step title="平台审核" />
          <el-step style="font-size: 8px" title="审核通过,凭入驻账号登录" />
        </el-steps>
        <div>
          <el-form-item label="机构性质" prop="resourceType">
            <c-radio
              constKey="orgResourceType"
              v-model="registerForm.resourceType"
            />
          </el-form-item>
          <el-form-item label="所在城市" prop="area">
            <AreaSelect v-model="registerForm.area" />
          </el-form-item>
          <el-form-item label="公司名称" prop="organizationName">
            <el-input
              maxlength="50"
              v-model="registerForm.organizationName"
              placeholder="输入公司名称（限制50字）"
            />
          </el-form-item>
          <el-form-item label="部落名称">
            <el-input
              disabled
              :value="
                registerForm.organizationName
                  ? registerForm.organizationName + '守护者部落'
                  : ''
              "
            />
          </el-form-item>
          <el-form-item label="营业执照" prop="businessLicense">
            <ImageUpload
              notip
              v-model="registerForm.businessLicense"
              text="上传营业执照"
            />
          </el-form-item>
          <el-form-item label="法人身份证号" prop="corporateIdCard">
            <el-input v-model="registerForm.corporateIdCard" maxlength="18" />
          </el-form-item>
          <el-form-item label="身份证正反面" prop="corporateIdCardF">
            <div>
              <ImageUpload
                notip
                v-model="registerForm.corporateIdCardF"
                text="上传身份证正面"
              />
              <ImageUpload
                notip
                v-model="registerForm.corporateIdCardO"
                text="上传身份证反面"
              />
            </div>
          </el-form-item>
          <el-form-item label="联系人" prop="contactsName">
            <el-input v-model="registerForm.contactsName" />
          </el-form-item>
          <el-form-item label="联系方式" prop="contactsPhone">
            <el-input v-model="registerForm.contactsPhone" maxlength="11" />
          </el-form-item>
          <el-form-item label="合同编号" prop="contractNo">
            <el-input v-model="registerForm.contractNo" />
          </el-form-item>
          <el-form-item label="签约合同" prop="contractUrl">
            <FileUpload
              :needCheckFile="false"
              v-model="registerForm.contractUrl"
              notip
            />
          </el-form-item>
          <el-form-item class="xy" prop="check">
            <el-checkbox v-model="registerForm.check" label="" size="large" />
            注册即代表您已阅读并同意
            <router-link to="/xy/1" target="_blank">
              <span>《服务协议》</span>
            </router-link>
            及
            <router-link to="/xy/2" target="_blank">
              <span>《隐私政策》</span>
            </router-link>
          </el-form-item>
        </div>
        <ElButton
          :loading="registerReq.loading.value"
          type="primary"
          size="large"
          style="width: 100%; margin-top: 20px"
          @click.prevent="handleRegister"
        >
          提交入驻申请
        </ElButton>
        <div class="sub-link">
          <ElLink type="primary" :underline="false" @click="formType = 'login'">
            去登录
          </ElLink>
        </div>
      </ElForm>
      <ElForm
        v-show="formType === 'reset'"
        ref="resetFormRef"
        :model="resetForm"
        :rules="resetRules"
        class="login-form"
      >
        <div class="title-container">
          <h3 class="title">忘记密码了? 🔒</h3>
        </div>
        <div>
          <ElFormItem prop="account">
            <ElInput
              v-model="resetForm.account"
              placeholder="用户名"
              type="text"
              tabindex="1"
            >
              <template #prefix>
                <SvgIcon name="i-ri:user-3-fill" />
              </template>
            </ElInput>
          </ElFormItem>
          <ElFormItem prop="captcha">
            <ElInput
              v-model="resetForm.captcha"
              placeholder="验证码"
              type="text"
              tabindex="2"
            >
              <template #prefix>
                <SvgIcon name="i-ic:baseline-verified-user" />
              </template>
              <template #append>
                <ElButton>发送验证码</ElButton>
              </template>
            </ElInput>
          </ElFormItem>
          <ElFormItem prop="newPassword">
            <ElInput
              v-model="resetForm.newPassword"
              type="password"
              placeholder="新密码"
              tabindex="3"
              show-password
            >
              <template #prefix>
                <SvgIcon name="i-ri:lock-2-fill" />
              </template>
            </ElInput>
          </ElFormItem>
        </div>
        <ElButton
          :loading="loading"
          type="primary"
          size="large"
          style="width: 100%; margin-top: 20px"
          @click.prevent="handleReset"
        >
          确认
        </ElButton>
        <div class="sub-link">
          <ElLink type="primary" :underline="false" @click="formType = 'login'">
            去登录
          </ElLink>
        </div>
      </ElForm>
    </div>
    <Copyright />
  </div>
</template>

<style lang="scss" scoped>
[data-mode='mobile'] {
  #login-box {
    position: relative;
    top: inherit;
    left: inherit;
    flex-direction: column;
    justify-content: start;
    width: 100%;
    height: 100%;
    border-radius: 0;
    box-shadow: none;
    transform: translateX(0) translateY(0);

    .login-banner {
      width: 100%;
      padding: 20px 0;

      .banner {
        position: relative;
        top: inherit;
        right: inherit;
        display: inherit;
        width: 100%;
        max-width: 375px;
        margin: 0 auto;
        transform: translateY(0);
      }
    }

    .login-form {
      width: 100%;
      min-height: auto;
      padding: 30px;
    }
  }

  .copyright {
    position: relative;
  }
}

:deep(input[type='password']::-ms-reveal) {
  display: none;
}

.bg-banner {
  position: fixed;
  z-index: 0;
  top: 0;
  width: 100%;
  height: 100%;
  // background: radial-gradient(
  //   circle at center,
  //   var(--g-container-bg),
  //   var(--g-bg)
  // );

  background: rgb(6 93 83) no-repeat;
}
.loginPage {
  width: 100vw;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

#login-box {
  margin: 10vh 0;
  position: relative;
  max-width: 950px;
  display: flex;
  justify-content: space-between;
  overflow: hidden;
  background-color: var(--g-container-bg);
  border-radius: 10px;
  box-shadow: var(--el-box-shadow);

  .login-banner {
    position: relative;
    width: 450px;
    overflow: hidden;
    background-color: var(--g-bg);
    &.login-banner1 {
      .banner {
        position: relative;
        top: 300px;
      }
    }
    .banner {
      width: 100%;

      @include position-center(y);
    }

    .logo {
      position: absolute;
      top: 20px;
      left: 20px;
      height: 30px;
      border-radius: 4px;
      box-shadow: var(--el-box-shadow-light);
    }
  }

  .login-form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 500px;
    min-height: 500px;
    padding: 50px;
    overflow: hidden;

    .title-container {
      position: relative;

      .title {
        margin: 0 auto 30px;
        font-size: 1.3em;
        font-weight: bold;
        color: var(--el-text-color-primary);
      }
    }
  }

  .el-form-item {
    margin-bottom: 24px;

    :deep(.el-input) {
      width: 100%;
      height: 48px;
      line-height: inherit;

      input {
        height: 48px;
      }

      .el-input__prefix,
      .el-input__suffix {
        display: flex;
        align-items: center;
      }

      .el-input__prefix {
        left: 10px;
      }

      .el-input__suffix {
        right: 10px;
      }
    }
  }

  :deep(.el-divider__text) {
    background-color: var(--g-container-bg);
  }

  .flex-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
  }

  .sub-link {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 20px;
    font-size: 14px;
    color: var(--el-text-color-secondary);

    .text {
      margin-right: 10px;
    }
  }
}

.copyright {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 20px;
  margin: 0;
}
</style>


<style lang="scss">
.login-form {
  .el-step__title {
    font-size: 10px;
  }
  --el-color-primary: rgb(12, 195, 175);
  --el-button-hover-bg-color: rgb(56, 187, 172);
  .xy {
    font-size: 14px;
    span {
      color: rgb(12, 195, 175);
    }
  }
}
</style>